package cn.sccdlg.ssm.dao;

import cn.sccdlg.ssm.domain.Permission;
import cn.sccdlg.ssm.domain.Role;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2020/10/27 21:25
 * 角色持久层
 */
@Repository
@Mapper
public interface IRoleDao {

    /**
     * 根据用户id查询出所有对应的角色（可含有对应权限资源信息）
     */
    @Select("SELECT * FROM role WHERE id IN (SELECT roleId FROM user_role WHERE userId=#{userId})")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions",column = "id",javaType = java.util.List.class,
                    many = @Many(select = "cn.sccdlg.ssm.dao.IPermissionDao.findPermissionByRoleId"))
    })
    List<Role> findRoleByUserId(String userId) throws Exception;

    /**
     * 查询所有角色
     */
    @Select("SELECT * FROM role")
    List<Role> findAll() throws Exception;

    /**
     * 保存角色信息
     * @param role 角色信息
     */
    @Insert("INSERT INTO role(id,roleName,roleDesc) VALUES(#{id},#{roleName},#{roleDesc})")
    void save(Role role);

    /**
     * 通过角色id查询角色信息（可含有对应权限资源信息）
     * @param roleId 角色id
     */
    @Select("SELECT * FROM role WHERE id=#{roleId}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "roleName",column = "roleName"),
            @Result(property = "roleDesc",column = "roleDesc"),
            @Result(property = "permissions",column = "id",javaType = java.util.List.class,
                    many = @Many(select = "cn.sccdlg.ssm.dao.IPermissionDao.findPermissionByRoleId"))
    })
    Role findById(String roleId);

    /**
     * 根据角色id查询权限资源信息
     * @param roleId 角色id
     */
    @Select("SELECT * FROM permission WHERE id NOT IN (SELECT permissionId FROM role_permission WHERE roleId=#{roleId})")
    List<Permission> findOtherPermissions(String roleId);

    /**
     * 保存角色与权限关联信息
     * @param roleId 角色id
     * @param permissionId 权限id
     */
    @Insert("INSERT INTO role_permission(roleId,permissionId) VALUES(#{roleId},#{permissionId})")
    void addPermissionToRole(@Param("roleId") String roleId, @Param("permissionId") String permissionId);

    /**
     * 删除角色与用户关联信息
     * @param roleId 角色id
     */
    @Delete("DELETE FROM user_role WHERE roleId=#{roleId}")
    void deleteFromUser2RoleByRoleId(String roleId);

    /**
     * 删除角色与权限关联信息
     * @param roleId 角色id
     */
    @Delete("DELETE FROM role_permission WHERE roleId=#{roleId}")
    void deleteFromRole2PermissionByRoleId(String roleId);

    /**
     * 删除角色信息
     * @param roleId 角色id
     */
    @Delete("DELETE FROM role WHERE id=#{roleId}")
    void deleteRoleById(String roleId);
}
